import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Tree, TreeNode} from "primeng/primeng";
import {InventoryService} from "../inventory.service";
import {ActivatedRoute} from "@angular/router";
import {StorageService} from "../../services/storage.service";
@Component({
  selector: 'app-add-inventory-location',
  templateUrl: './add-inventory-location.component.html',
  styleUrls: ['./add-inventory-location.component.scss']
})
export class AddInventoryLocationComponent implements OnInit {
  filesTree4;
  selectedFile;
  @Output() closeMask = new EventEmitter();
  @Output() addTree = new EventEmitter();
  @Output() updateTree = new EventEmitter();
  @Input() pnAnddataSource;
  @Input() treeState;
  @Input() sid;
  @Output() updateDev = new EventEmitter(); //库存位置
  selected;
  display;
  submitData;
  treeData;
  constructor(
    private inventoryService:InventoryService,
    private route:ActivatedRoute,
    private storageService:StorageService
    ) { }

  ngOnInit() {
    this.display = true;
    if(this.treeState === 'update'){
      this.pnAnddataSource = this.inventoryService.deepClone(this.pnAnddataSource);
      this.submitData = {
        'sid':this.pnAnddataSource['sid'],
        "inventories":this.pnAnddataSource['data']
      }
    }
    this.queryMeterial();
  }
  queryMeterial(){
    this.inventoryService.queryStorageLocationTree().subscribe(data =>{
      this.treeData = data;
      console.log(this.treeData['father']);
      let nodeArr = [];
      nodeArr.push(this.treeData);
      this.filesTree4 = this.inventoryService.changeObjectName(nodeArr,'label','name');
     console.log(this.selectedFile);
    });
  }
  // selectedTree($event){
  //    console.log(this.selectedFile)
  // }

  formSubmit(bool){
      if(this.treeState ==='update'){
        let index = this.storageService.getLocationIndex('locationIndex');
        this.submitData.inventories[index]['location'] = this.selectedFile.label;
        this.submitData.inventories[index]['location_id'] = this.selectedFile.did;
        this.inventoryService.modifiedLocation(this.submitData).subscribe(data=>{
          this.updateDev.emit(this.submitData);

          },(err:Error)=>{
            alert(err)
        })
      }else{
        this.addTree.emit(this.selectedFile);
      }
    }
  closeLocationMask(bool){
    this.closeMask.emit(bool)
  }
   deepTree(tree,label){
     for(let i  in tree){
       if(tree[i]['label'] === label){
         return {obj:tree[i]}
       }
       if(Number(i) == tree.length-1){
         this.deepTree(tree[i]['children'],label);
       }
     }
   }
}
